<template>

	<view class="qiangqiangUser" style="background: #fff;">
		<cover-view class="navBar">
			<cover-view class="navBar_1"></cover-view>
			<cover-view class="navBarTop">
				<cover-view class="left">
					<cover-image @tap="back" class="img" src="/static/img/index/24.png"></cover-image>
				</cover-view>
				<cover-view class="navBarTop_text">{{come?'我':userInfo?.userName}}的墙墙</cover-view>

				<cover-view class="center">
					<slot name="center"></slot>
				</cover-view>
				<cover-view class="right">
					<slot name="right"></slot>
				</cover-view>
			</cover-view>
		</cover-view>
		<cover-view @tap="fabClick" class="floating-button">
			<cover-image @tap="fabClick" class="plus-icon" src="../../static/img/jiahao.png"></cover-image>
		</cover-view>

		<view class="" style="padding-top: 88rpx;">
			<view v-if="!come" class="masterWraps">
				<view class="masterWrap">
					<view class="masterInfo">
						<image class="masterInfoImg" mode="aspectFill" :src="httpUrl+'/app/file/viewFile?fileId='+userInfo?.avatar"></image>
						<view class="masterInfoText">
							<view class="masterInfoName">
								<text style="color: #262626;font-size: 32rpx;font-weight: 600;">{{userInfo?.userName}}</text>
							</view>
							<view class="masterInfoName">
								<text style="color: #595959;font-size: 28rpx;">{{userInfo?.autograph}}</text>
							</view>
							<view class="masterInfoName">
								<text style="color: #8C8C8C;font-size: 28rpx;">ID: {{userInfo?.userId.slice(-9)}}</text>
							</view>
						</view>
					</view>
					<view class="fansWrap">
						<view class="fanWrap">
							<text class="fansTop">{{userInfo?.followTotalCount}}</text>
							<text class="fansBottom">关注</text>
						</view>
						<view class="fanWrap">
							<text class="fansTop">{{userInfo?.fansTotalCount}}</text>
							<text class="fansBottom">粉丝</text>
						</view>
						<view class="fanWrap">
							<text class="fansTop">{{userInfo?.likeTotalCount}}</text>
							<text class="fansBottom">获赞</text>
						</view>
					</view>
					<view class="handleWrap">
						<view @tap="toOrFollow" v-if="userInfo?.flagFollow=='FOLLOW'" class="leftHand" style="background: #E4E2FC;border: 2rpx solid #CAC5FA;">
							<text style="color: #6B64D3;font-size: 32rpx;font-weight: bold;">已关注</text>
						</view>
						<view @tap="toOrFollow" v-else class="leftHand">
							<image class="addImg" src="../../static/img/plus.png"></image>
							<text style="color: #fff;font-size: 32rpx;margin-left: 6rpx;">关注</text>
						</view>
						<view class="rightHand">
							<image v-if="userInfo?.storeId" @tap="toPersonStore(userInfo?.storeId)" class="userImg" src="@/static/icons/my/shopping.png"></image>
							<image @tap="chat" class="userImg" src="../../static/img/userleft.png"></image>
							<image @tap="chatShare" class="userImg" src="../../static/img/userRight.png"></image>
						</view>
					</view>
				</view>

			</view>
			<view class="main" :class="{comes:come}">
				<view @longpress="longpress(item,index)" v-for="(item,index) in qiangList" :key="index" class="wrap">
					<view class="upWrap">
						<image class="header" mode="aspectFill" :src="userInfo?.avatar?`${httpUrl}/app/file/viewFile?fileId=${userInfo.avatar}`:'../../static/img/userImg.png'">
						</image>
						<view class="userInfo">
							<view class="userName">{{userInfo?.userName}}</view>
							<view class="userTime">发布于 {{item.updateTime}}</view>
						</view>
					</view>

					<view @tap="toMore(item)" class="middleWrap">
						<view v-if="item.trendsType=='FORWARD'" class="textWrap">
							<text @tap.stop="toUser(item.forwardUserId)" style="color: #6B64D3;">@{{item.forwardUserName}}</text>
							<text style="margin-left: 5rpx;">{{item.forwardContent}}</text>
						</view>
						<view v-else class="textWrap">{{item.title}}</view>
						<view v-if="item.fileType=='PICTURE' && item.attachmentIds" class="imgWrap">
							<image @tap.stop="previewImage(item?.attachmentIds?.split(','),n)" class="img" :style="{
							    width: item?.attachmentIds?.split(',').length <3   
							      ? '300rpx':'180rpx',
									height:item?.attachmentIds?.split(',').length <3?'':'210rpx' 
							  }" :mode="item?.attachmentIds?.split(',').length < 3 ? 'widthFix' : 'aspectFill'" v-for="(m, n) in (item?.attachmentIds || '').split(',')" :key="n" :src="`${httpUrl}/app/file/viewFile?fileId=${m}`"></image>
						</view>
						<view v-if="item.fileType=='VIDEO'" class="imgWrap">
							<view class="videoWraps">
								<video class="video" objectFit="contain" :style="{height: Number(item.attachFiles[0].height / item.attachFiles[0].width * 340).toFixed(0) + 'rpx'}" :poster="`${httpUrl}/app/file/viewFile?fileId=${item.attachmentIds}&process=video/snapshot,t_1000,f_jpg,w_${item.attachFiles[0].width},h_${item.attachFiles[0].height},m_fast`" :src="`${httpUrl}/app/file/viewFile?fileId=${item.attachmentIds}`"></video>
							</view>
						</view>
					</view>
					<view class="downWrap">
						<view @tap="share(item.id)" class="fenxiang">
							<image class="fenxiangImg" src="../../static/img/upload-2.png"></image>
							<text class="fenxiangText">分享</text>
						</view>
						<view v-if="item.attachFiles.length>0" @tap="xiazai(item)" class="fenxiang" style="position: relative;">
							<image class="fenxiangImg" src="../../static/img/xiazai.png"></image>
							<text class="fenxiangText">下载</text>
							<text v-if="item.percent>0" style="position: absolute;right: -50rpx;">
								{{item.percent}}%
							</text>
						</view>
						<view class="rightWrap">
							<image @tap="toPraise(item)" v-if="item.flagPraise=='LIKE'" class="rightImg" src="../../static/img/dianzan.png">
							</image>
							<image @tap="toPraise(item)" v-else class="rightImg" src="../../static/img/base-icon-like.png">
							</image>
							<text class="rightText">{{item.praiseCount}}</text>
							<image @tap="remark(item,index)" class="rightImg" src="../../static/img/rrame.png"></image>
							<text @tap="remark(item,index)" class="rightText">{{item.commentsCount}}</text>
							<image @tap="toReward(item,index)" class="rightImg" src="../../static/img/Frame 1321318967.png">
							</image>
							<text @tap="toReward(item,index)" class="rightText">{{item.rewardNum}}</text>
							<image @tap="goMore(item,index)" class="rightImg" src="../../static/img/3-dots-horizontal .png">
							</image>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view style="background: #F4F6FA;display: flex;align-items: center;justify-content: center;">
			<uni-load-more :status="moreText"></uni-load-more>
		</view>
	</view>
	<cover-view class="hongbao_jifen" v-if="!isTimer">
		<cover-image v-if="secondaryCountdown!=0" class="hongbaos_imgs" src="../../static/img/hongbao_loading.gif"></cover-image>
		<cover-view v-if="secondaryCountdown!=0" class="hongbaos_text_wrap">
			<cover-view>{{countdown}}s</cover-view>
		</cover-view>
		<cover-image v-else class="hongbaos_imgs" src="../../static/img/hongbao_open.png"></cover-image>
	</cover-view>
</template>

<script setup lang="ts">
	import { onReachBottom, onShow, onLoad, onPullDownRefresh, onPageScroll } from '@dcloudio/uni-app'
	import { ref, computed } from 'vue'
	import { saveOrDleTrendsPraise, saveFollow, queryUserHome, delTrendsState } from '@/utils/api/index.ts'
	import { getUserImInfo } from '@/utils/api/userInfo.ts'
	import { useCounterStore } from '@/stores/counter';
	import { TUILogin } from '@tencentcloud/tui-core';
	// #ifdef APP-PLUS || H5
	import { TUIChatKit } from '../../pages/TUIKit';
	TUIChatKit.init();
	// #endif
	const httpUrl = ref(getApp().globalData.baseUrl)
	const back = () => {
		uni.navigateBack()
	}
	const isTimer = ref(false)
	// 积分倒计时
	const counterStore = useCounterStore();
	const countdown = computed(() => counterStore.mainCountdown)
	const secondaryCountdown = computed(() => counterStore.secondaryCountdown)
	onPageScroll(() => {
		if (!isTimer.value) {
			counterStore.resetSecondaryAndResumeMain()
		}
	})
	// 下载
	const xiazai = (item : any) => {
		if (item.fileType == 'VIDEO') {
			const downloadTask = uni.downloadFile({
				url: `${httpUrl.value}/app/file/viewFile?fileId=${item.attachFiles[0].id}`,
				success: (res) => {
					if (res.statusCode === 200) {
						uni.saveVideoToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function () {
								uni.showToast({
									title: '下载成功',
									icon: 'none'
								});
								item.percent = 0
							}
						});
					}
				}
			});
			downloadTask.onProgressUpdate((res) => {
				item.percent = res.progress
			});
		}
		if (item.fileType == 'PICTURE') {
			const imgList = item.attachFiles.map((i : any) => {
				return `${httpUrl.value}/app/file/viewFile?fileId=${i.id}`
			})
			let num = 0
			imgList.map((it : string) => {
				uni.saveImageToPhotosAlbum({
					filePath: it,
					success: function () {
						num++
						item.percent = (num / imgList.length * 100).toFixed(0)
						if (num == imgList.length) {
							uni.showToast({
								title: '下载成功',
								icon: 'none'
							});
							item.percent = 0
						}
					}
				});
			})

		}
	}
	// 发布墙墙
	const fabClick = () => {
		uni.navigateTo({
			url: `/pages/release/release`
		})
	}
	// 点赞/取消
	const toPraise = async (item : any) => {
		const res = await saveOrDleTrendsPraise({ data: { trendsId: item.id } })
		if (res.code == 200) {
			item.flagPraise = res.data.likeTypeEnum.value
			item.praiseCount = res.data.appUserTrends.praiseCount
			if (res.data.redAmount > 0) {
				uni.showToast({
					title: `点赞成功!抢到${res.data.redAmount}个钻石红包`,
					icon: 'none'
				});
			} else {
				uni.showToast({
					title: res.data.msg,
					icon: 'none'
				});
			}
		}
	}
	const longpress = (item, index) => {
		if (uni.getStorageSync('userInfo').userId != item.userId) {
			return;
		}
		uni.showActionSheet({
			itemList: ['删除'],
			success: (e) => {

				uni.showModal({
					title: '提示',
					content: '是否删除该墙墙?',
					success: (e) => {
						if (e.confirm) {
							uni.showLoading({
								title: '加载中...',
								mask: true
							})
							delTrendsState({ data: { id: item.id } }).then((res) => {
								uni.showToast({
									title: '删除成功!',
									icon: 'none'
								})
								qiangList.value.splice(index, 1)
							})
						}
					}
				})
			}
		})
	}
	// 聊天
	const getUserInfo = async () => {
		const { userID } = TUILogin.getContext();
		const userRes = await getUserImInfo()
		if (userID && userID == userRes.data.imUserId) {
			return
		}
		if (userID && userID != userRes.data.imUserId) {
			TUILogin.logout();
		}
		await TUILogin.login({
			SDKAppID: 1600043419,
			userID: userRes.data.imUserId,
			userSig: userRes.data.imUserSign,
			useUploadPlugin: true,
			framework: `vue3`
		})
	}

	// 跳转到店铺详情
	const toPersonStore = (storeId) => {
		uni.navigateTo({
			url: `/pages/shop/index?id=${storeId}`
		})
	}

	const chat = async () => {
		await getUserInfo()
		const conversationID = `C2C${userId.value}`;
		uni.navigateTo({ url: `/pages/TUIKit/components/TUIChat/index?conversationID=${conversationID}` });
	}
	const chatShare = async () => {
		uni.navigateTo({
			url: `/pages/qiangqiang/friendList?userId=${userId.value}&areaType=${areaType.value}`,
			animationType: 'slide-in-bottom',
			animationDuration: 250
		})
	}
	// 评论
	const remark = (item : any, index : number) => {
		uni.navigateTo({
			url: `/pages/qiangqiang/popup?id=${item.id}&index=${index}`,
			animationType: 'slide-in-bottom',
			animationDuration: 250
		})
	}
	// 预览图片
	const previewImage = (list : any, n : number) => {
		const imgList = list.map((item : any) => {
			return `${httpUrl.value}/app/file/viewFile?fileId=${item}`
		})
		uni.previewImage({
			urls: imgList,
			current: n,
			longPressActions: {
				itemList: ['保存图片'],
				success: function (data) {
					uni.closePreviewImage()
					// 获取当前长按的图片 URL  
					const currentImageUrl = imgList[data.index];
					// 调用保存图片到相册的接口  
					uni.saveImageToPhotosAlbum({
						filePath: currentImageUrl,
						success: function () {
							uni.showToast({
								title: '保存成功',
								icon: 'none'
							});
						},
						fail: function (err) {
							console.error(err);
							uni.showToast({
								title: '保存失败',
								icon: 'none'
							});
						}
					});
				}
			}
		});
	}
	// 打赏
	const toReward = (item : any, index : number) => {
		uni.navigateTo({
			url: `/pages/qiangqiang/reward?id=${item.id}&index=${index}`,
			animationType: 'slide-in-bottom',
			animationDuration: 250
		})
	}
	// 跳转到帖子用户详情
	const toUser = (userId : string) => {
		uni.navigateTo({
			url: '/pages/qiangqiang/user?userId=' + userId
		})
	}
	// 关注或取消关注用户
	const toOrFollow = async () => {
		const res = await saveFollow({ data: { userId: userId.value } })
		if (res.code == 200) {
			userInfo.value.flagFollow = res.data
			uni.showToast({
				title: res.msg,
				icon: 'none'
			});
		}
	}
	// 去帖子详情
	const toMore = (item : any) => {
		let url = '/pages/qiangqiang/qiangMore?id='
		if (item.trendsType == 'FORWARD') {
			url += item.forwardTrendsId;
		} else {
			url += item.id;
		}
		if (isTimer.value) {
			url += '&isTimer=1'
		}
		uni.navigateTo({
			url
		})
	}
	// 跳转到帖子更多
	const goMore = (item : any, index : number) => {
		uni.navigateTo({
			url: `/pages/qiangqiang/more?id=${item.id}&index=${index}&avatar=${userInfo.value.avatar}&userName=${userInfo.value.userName}`,
			animationType: 'slide-in-bottom',
			animationDuration: 250
		})
	}
	// 分享
	const share = (id : string) => {
		uni.navigateTo({
			url: `/pages/qiangqiang/friendList?id=${id}&areaType=${areaType.value}`,
			animationType: 'slide-in-bottom',
			animationDuration: 250
		})
	}
	// 获取列表数据
	const pageNo = ref(1)
	const qiangList = ref<any>([])
	const userInfo = ref()
	const getList = async () => {
		const data = {
			pageNo: 1,
			pageSize: 5,
			userId: userId.value
		}
		const res = await queryUserHome({ data: data })
		userInfo.value = res.data
		qiangList.value = res.data.appUserTrendsPageInfo.list
		uni.stopPullDownRefresh()
	}
	const userId = ref('')
	const areaType = ref('')
	const come = ref('')
	onLoad((option) => {
		userId.value = option.userId
		areaType.value = option.areaType
		come.value = option.come
		console.log(option.value)
		isTimer.value = option.isTimer ? true : false;
		getList()
	})
	onShow(() => {
		uni.$once('refreshData', function () {
			getList()
		})
	})
	// 下拉刷新
	onPullDownRefresh(() => {
		pageNo.value = 1
		getList()
	})
	// 触底加载
	const moreText = ref('loading')
	onReachBottom(async () => {
		pageNo.value = pageNo.value + 1
		const data = {
			pageNo: pageNo.value,
			pageSize: 5,
			userId: userId.value
		}
		const res = await queryUserHome({ data: data })
		if (res.data.appUserTrendsPageInfo.list.length > 0) {
			qiangList.value.push(...res.data.appUserTrendsPageInfo.list)
		} else {
			moreText.value = 'no-more'
		}
	})
</script>

<style lang="scss" scoped>
	.masterWraps {
		width: 100%;
		height: 415rpx;

		.masterWrap {
			width: 94%;
			height: 415rpx;
			margin-left: 3%;
			background: #fff;

			.masterInfo {
				width: 100%;
				height: 135rpx;
				margin-top: 32rpx;
				margin-bottom: 32rpx;
				display: flex;

				.masterInfoImg {
					width: 135rpx;
					height: 135rpx;
					border-radius: 70rpx;
					margin-left: 12rpx;
				}

				.masterInfoText {
					height: 135rpx;
					margin-left: 16rpx;

					.masterInfoName {
						height: 48rpx;
						display: flex;
						align-items: center;
					}
				}
			}

			.fansWrap {
				width: 100%;
				height: 130rpx;
				background: #F4F6FA;
				border-radius: 24rpx;
				display: flex;

				.fanWrap {
					width: 33.33%;
					height: 130rpx;
					display: flex;
					flex-direction: column;
					align-items: center;

					.fansTop {
						color: #262626;
						font-size: 36rpx;
						font-weight: bold;
						margin-top: 16rpx;
					}

					.fansBottom {
						color: #8C8C8C;
						font-size: 24rpx;
						margin-top: 8rpx;
					}
				}
			}

			.handleWrap {
				width: 100%;
				height: 80rpx;
				margin-top: 20rpx;
				display: flex;
				align-items: center;
				justify-content: justify-content;

				.leftHand {
					width: 300rpx;
					height: 80rpx;
					background: #6B64D3;
					border-radius: 52rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					.addImg {
						width: 36rpx;
						height: 36rpx;
					}
				}

				.rightHand {
					flex-grow: 1;
					height: 80rpx;
					display: flex;
					align-items: center;
					justify-content: space-around;

					.userImg {
						width: 80rpx;
						height: 80rpx;
					}
				}
			}
		}
	}

	.main {
		width: 100%;
		min-height: 70vh;
		background: #F4F6FA;
		position: relative;
		padding-top: 5rpx;
		padding-bottom: 25rpx;

		.wrap {
			width: 95%;
			margin-left: 2.5%;
			background: #fff;
			border-radius: 32rpx;
			margin-top: 24rpx;
			position: relative;
			z-index: 2;

			.upWrap {
				width: 95%;
				height: 128rpx;
				margin-left: 2.5%;
				display: flex;
				align-items: flex-end;

				.header {
					width: 96rpx;
					height: 96rpx;
					border-radius: 48rpx;
				}

				.userInfo {
					width: 400rpx;
					height: 96rpx;
					margin-left: 24rpx;

					.userName {
						width: 100%;
						height: 48rpx;
						color: #262626;
						font-size: 32rpx;
						font-weight: bold;
						display: flex;
						align-items: center;
					}

					.userTime {
						width: 100%;
						height: 48rpx;
						color: #8C8C8C;
						font-size: 28rpx;
						display: flex;
						align-items: center;
					}
				}

				.follow {
					width: 120rpx;
					height: 96rpx;
					margin-left: auto;
					display: flex;
					align-items: center;
					justify-content: center;

					.toFollow {
						width: 120rpx;
						height: 52rpx;
						border-radius: 26rpx;
						background: rgba(89, 83, 192, 1);
						color: #6B64D3;
						display: flex;
						align-items: center;
						justify-content: center;
					}

					.beFollow {
						width: 120rpx;
						height: 52rpx;
						border-radius: 26rpx;
						background: #E4E2FC;
						border: 2rpx solid #CAC5FA;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}
			}

			.middleWrap {
				width: 95%;
				margin-left: 2.5%;

				.textWrap {
					width: 100%;
					height: 70rpx;
					display: flex;
					align-items: center;
					color: #262626;
					font-size: 28rpx;
				}

				.imgWrap {
					width: 100%;
					display: flex;
					flex-wrap: wrap;
					position: relative;

					.img {
						margin-right: 14rpx;
						margin-bottom: 14rpx;
					}

					.videoWraps {
						width: 100%;
						display: flex;
						justify-content: center;

						.video {
							width: 680rpx;
							background: #000;
							display: flex;
							align-items: center;
							justify-content: center;
						}
					}
				}
			}

			.downWrap {
				width: 95%;
				height: 112rpx;
				margin-left: 2.5%;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.fenxiang {
					width: 104rpx;
					height: 48rpx;
					display: flex;
					align-items: center;

					.fenxiangImg {
						width: 36rpx;
						height: 36rpx;
					}

					.fenxiangText {
						color: #8C8C8C;
						font-size: 24rpx;
						margin-left: 8rpx;
					}
				}

				.rightWrap {
					width: 410rpx;
					height: 48rpx;
					display: flex;
					align-items: center;
					justify-content: flex-end;

					.rightImg {
						width: 36rpx;
						height: 36rpx;
						margin-left: 8rpx;
					}

					.rightText {
						color: #8C8C8C;
						font-size: 24rpx;
						margin-left: 8rpx;
					}
				}
			}
		}
	}

	.comes {
		min-height: 100vh;
	}

	/* 悬浮按钮样式 */
	.floating-button {
		position: fixed;
		bottom: 20px;
		right: 20px;
		width: 50px;
		height: 50px;
		background-color: #6B64D3;
		border-radius: 50%;
		/* 调整后的阴影效果 */
		box-shadow: 2px 4px 10px rgba(0, 0, 0, 0.3);
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		/* 可选：增加触摸反馈效果 */
		transition: box-shadow 0.3s ease, transform 0.3s ease;
	}

	/* 触摸反馈效果 */
	.floating-button:active {
		box-shadow: 4px 6px 12px rgba(0, 0, 0, 0.4);
		transform: translateY(-2px);
	}

	.plus-icon {
		width: 32px;
		height: 32px;
	}

	.qiangqiangUser {
		padding-top: var(--status-bar-height);
	}

	.navBar {
		position: fixed;
		z-index: 99;
		top: 0;
		background: #fff;
		left: 0;
		width: 100%;
	}

	.navBar_1 {
		background: #fff;
		width: 100%;
		height: var(--status-bar-height);
	}

	.navBarTop {
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 88rpx;
		// margin-top: 28rpx;
		padding-top: 28rpx;
		background: #fff;
		z-index: 9;

		.left {
			position: absolute;
			left: 32rpx;
			height: 88rpx;
			display: flex;
			align-items: center;

			.img {
				width: 36rpx;
				height: 30rpx;
			}
		}

		.navBarTop_text {
			color: #333333;
			font-size: 32rpx;
		}

		.right {
			display: flex;
			align-items: center;
			height: 88rpx;
			position: absolute;
			right: 32rpx;
		}
	}

	// 悬浮红包积分
	.hongbao_jifen {
		position: fixed;
		bottom: 20px;
		left: 20px;
		width: 75px;
		height: 75px;
		z-index: 999;
	}

	.hongbaos_imgs {
		width: 75px;
		height: 75px;
		position: absolute;
		left: 0;
		top: 0;
	}

	.hongbaos_text_wrap {
		color: #fff;
		position: absolute;
		width: 75px;
		top: 60%;
		font-size: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>